package com.samuel.oss;


import com.aliyun.oss.OSSClient;

import java.io.File;

/**
 * 阿里云oss服务器上传图片
 */
public class AliyunOss {

    /**
     * 上传图片到阿里云服务器
     * @param file  上传的图片
     * @param fileName   图片名称
     * @return oss上图片的地址
     */
    public static String uploadAliyunOss(File file, String fileName) {
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = "LTAI2t4yuQe8BTiV";
        String accessKeySecret = "sPiWCuVFaNG31yj0i5coV0hbwLuxfz";
        String bucketName = "blog-image";

        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        // 如果不存在这个bucketName 就创建
        boolean flag = ossClient.doesBucketExist(bucketName);
        if (!flag) {
           ossClient.createBucket(bucketName);
        }

        // 上传图片
        ossClient.putObject(bucketName, fileName, file);
        String saveUrl = endpoint + File.separator + fileName;

        // 关闭资源
        ossClient.shutdown();
        return saveUrl;
    }


}
